const http = require("./http");
const nodeEcharts = require("node-echarts");
const { javaServerAddress, token, companyId, colors } = require("../config");

const httpOperations = {
  url: "",
  method: "get",
  headers: {
    Authorization: token
  },
  qs: {
    companyId
  }
};
/**
 * 生成电流统计图配置
 * @param {Object} param0
 */
function genCurrentOption({
  title,
  type,
  maxValue,
  thresholdValue,
  maxValueDate,
  x,
  y
}) {
  let danwei = "";
  let markLine = {};
  let textColor = "#000";
  switch (type) {
    case 12:
    case 13:
    case 14:
      danwei = "A";
      break;
    case 63:
      danwei = "mA";
      break;
  }
  const subtext = () => {
    if (Number(maxValue) > Number(thresholdValue)) {
      markLine = {
        silent: true,
        data: [
          {
            yAxis: thresholdValue
          }
        ]
      };
      textColor = "red";
      return `(实测值/报警值 ${maxValue}${danwei} > ${thresholdValue}${danwei})`;
    } else {
      return `(实测值/报警值 ${maxValue}${danwei} < ${thresholdValue}${danwei})`;
    }
  };

  return {
    title: {
      // left: "center",
      // text: `${title}【时间${maxValueDate}】`,
      // subtext: subtext(),
      // textStyle: {
      //   fontSize: 15
      // },
      // subtextStyle: {
      //   color: textColor
      // }
    },
    xAxis: {
      type: "category",
      data: x,
      boundaryGap: false,
      splitLine: {
        show: true
      },
      axisLabel: {
        interval: 0,
        formatter(val) {
          return val.substr(5, val.length);
        }
      }
    },
    yAxis: {
      name: `电流 (${danwei})`,
      type: "value",
      splitLine: {
        show: true
      }
    },
    grid: {
      top: "5%",
      bottom: "15%",
      right: "5%",
      show: true,
      backgroundColor: "#C0C0C0"
    },
    series: [
      {
        data: y,
        type: "line",
        symbol: "rect",
        symbolSize: 10,
        markLine
      }
    ]
  };
}

/**
 * 生成温度统计图配置
 * @param {Object} param0
 */
function genTempureOption({
  title,
  type,
  maxValue,
  thresholdValue,
  maxValueDate,
  x,
  y
}) {
  let danwei = "℃";
  let markLine = {};
  let textColor = "#000";
  const subtext = () => {
    if (Number(maxValue) > Number(thresholdValue)) {
      markLine = {
        silent: true,
        data: [
          {
            yAxis: thresholdValue
          }
        ]
      };
      textColor = "red";
      return `(实测值/报警值 ${maxValue} ${danwei}> ${thresholdValue}${danwei})`;
    } else {
      return `(实测值/报警值 ${maxValue} ${danwei}< ${thresholdValue}${danwei})`;
    }
  };
  return {
    title: {
      // left: "center",
      // text: `${title}【时间${maxValueDate}】`,
      // subtext: subtext(),
      // textStyle: {
      //   fontSize: 15
      // },
      // subtextStyle: {
      //   color: textColor
      // }
    },
    xAxis: {
      type: "category",
      data: x,
      boundaryGap: false,
      splitLine: {
        show: true
      },
      axisLabel: {
        interval: 0,
        formatter(val) {
          return val.substr(5, val.length);
        }
      }
    },
    yAxis: {
      name: `温度(${danwei})`,
      type: "value",
      splitLine: {
        show: true
      }
    },
    grid: {
      top: "5%",
      bottom: "15%",
      right: "5%",
      show: true,
      backgroundColor: "#C0C0C0"
    },
    series: [
      {
        data: y,
        type: "line",
        symbol: "rect",
        symbolSize: 10,
        markLine
      }
    ]
  };
}

/**
 * 生成谐波统计图配置
 * @param {*} info
 */
function genHarmonicOption(harmonicInfo) {
  const curve = harmonicInfo.curve;
  const info = harmonicInfo.info;
  let THDa = harmonicInfo.info[56].maxValue;
  let THDb = harmonicInfo.info[57].maxValue;
  let THDc = harmonicInfo.info[58].maxValue;
  const formatObj = type => {
    return [
      curve[3][type],
      curve[5][type],
      curve[7][type],
      curve[9][type],
      curve[11][type]
    ];
  };
  const formatSeries = () => {
    const one = formatObj("a");
    const two = formatObj("b");
    const three = formatObj("c");

    return [
      {
        type: "bar",
        barGap: 0,
        data: [THDa, ...one]
      },
      {
        type: "bar",
        barGap: 0,
        data: [THDb, ...two]
      },
      {
        type: "bar",
        barGap: 0,
        data: [THDc, ...three]
      }
    ];
  };

  const xRay = ["THD", ...Object.keys(curve)];
  const series = formatSeries();
  const subtext = () => {
    let A = null,
      B = null,
      C = null;
    if (info[56].maxValue > info[56].thresholdValue) {
      A = `A相畸变率 ${info[56].maxValue}% > ${info[56].thresholdValue} %；`;
    } else {
      A = `A相畸变率 ${info[56].maxValue}% < ${info[56].thresholdValue} %；`;
    }

    if (info[57].maxValue > info[57].thresholdValue) {
      B = `B相畸变率 ${info[57].maxValue}% > ${info[57].thresholdValue} %；`;
    } else {
      B = `B相畸变率 ${info[57].maxValue}% < ${info[57].thresholdValue} %；`;
    }

    if (info[58].maxValue > info[58].thresholdValue) {
      C = `C相畸变率 ${info[58].maxValue}% > ${info[58].thresholdValue} %；`;
    } else {
      C = `C相畸变率 ${info[58].maxValue}% < ${info[58].thresholdValue} %；`;
    }
    return `${A}${B}${C}`;
  };
  return {
    title: {
      // left: "center",
      // text: `三相电压谐波畸变率最大值【时间：${harmonicInfo.maxValueDate}】`,
      // textStyle: {
      //   fontSize: 15
      // },
      // subtext: subtext(),
      // subtextStyle: {
      //   color: "#000"
      // }
    },

    color: ["#003366", "#006699", "#4cabce", "#e5323e"],
    grid: {
      top: "5%",
      bottom: "15%"
    },
    xAxis: {
      type: "category",
      data: xRay,
      splitLine: {
        show: true
      }
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true
      }
    },
    series: series
  };
}

/**
 * 生成中性线相关配置
 * @param {*} neutralLineInfo
 */
function genNeutralLineOption(info) {
  const yRay = info.y;
  const xRay = info.x;
  const arrText = [
    "中性线电流",
    "三相电流不平衡度",
    "A相三次谐波电流",
    "B相三次谐波电流",
    "C相三次谐波电流"
  ];
  const arrColor = ["#FF7F50", "#87CEFA", "#DF83DC", "#30CD30", "#6C9AEE"];
  const subtext = () => {
    const MAX_info = info["maxVal-info"];
    let str = `三相电流不平衡度：${MAX_info[25]}%；\n
            A相3次谐波电流：${MAX_info[35]}A；\n
            B相3次谐波电流：${MAX_info[36]}A；\n
            C相3次谐波电流：${MAX_info[37]}A；\n
            温度：${MAX_info[8]}℃；`;
    return info.maxValue > info.thresholdValue
      ? `实测值${info.maxValue}A > 报警值${info.thresholdValue}A\n${str}`
      : `实测值${info.maxValue}A < 报警值${info.thresholdValue}A\n${str}`;
  };

  const series = () => {
    let newArr = Object.keys(yRay);
    return newArr.map((item, index) => {
      return {
        data: yRay[item],
        name: arrText[index],
        type: "line",
        smooth: true,
        areaStyle: {
          normal: {}
        },
        yAxisIndex: item == 25 ? 1 : 0
      };
    });
  };
  return {
    title: {
      // left: "center",
      // text: `中性线电流最大值【时间${info.maxValDate}】`,
      // textStyle: {
      //   fontSize: 15
      // },
      // subtext: subtext(),
      // subtextStyle: {
      //   color: "#000"
      // }
    },
    color: arrColor,
    xAxis: {
      data: xRay,
      type: "category",
      boundaryGap: false,
      splitLine: {
        show: true
      },
      axisLabel: {
        interval: 0,
        formatter(val) {
          return val.substr(5, val.length);
        }
      }
    },
    grid: {
      top: "5%",
      bottom: "25%"
    },
    legend: {
      x: "center",
      bottom: "5%",
      data: arrText
    },
    yAxis: [
      {
        type: "value",
        name: "电流(A)",
        splitLine: {
          show: true
        }
      },
      {
        type: "value",
        name: "三相电流不平衡度(%)"
      }
    ],
    series: series()
  };
}

// 获取电流、温度相关数据
async function getHttpDatas(deviceId) {
  const apiAddress = `${javaServerAddress}/report/detail-ct`;
  const _httpOperations = { ...httpOperations };
  _httpOperations.url = apiAddress;
  _httpOperations.qs = { ..._httpOperations.qs, deviceId };
  try {
    const { statusCode, body } = await http(apiAddress, _httpOperations);
    if (statusCode === 200 && body) {
      const resData = JSON.parse(body);
      const {
        data: {
          info: { current: currentInfo, temperature: temperatureInfo }
        },
        code
      } = resData;

      if (code === 200) {
        return {
          currentInfo,
          temperatureInfo
        };
      }
      return new Promise.reject(resData);
    }
  } catch (error) {
    if (error) {
      return Promise.reject({
        code: 400,
        error: error
      });
    }
  }
}

// 获取谐波相关数据
async function getXieBoDatas(deviceId) {
  const apiAddress = `${javaServerAddress}/report/detail-xb`;
  const _httpOperations = { ...httpOperations };
  _httpOperations.url = apiAddress;
  _httpOperations.qs = { ..._httpOperations.qs, deviceId };
  try {
    const { statusCode, body } = await http(apiAddress, _httpOperations);
    if (statusCode === 200 && body) {
      const resData = JSON.parse(body);
      const { data, code } = resData;
      if (code === 200) {
        return {
          harmonicInfo: data
        };
      }
      return new Promise.reject(resData);
    }
  } catch (error) {
    if (error) {
      return Promise.reject({
        code: 400,
        error: error
      });
    }
  }
}

// 获取中性线相关数据
async function getZhongXingXianDatas(deviceId) {
  const apiAddress = `${javaServerAddress}/report/detail-lx`;
  const _httpOperations = { ...httpOperations };
  _httpOperations.url = apiAddress;
  _httpOperations.qs = { ..._httpOperations.qs, deviceId };
  try {
    const { statusCode, body } = await http(apiAddress, _httpOperations);
    if (statusCode === 200 && body) {
      const resData = JSON.parse(body);
      const { data, code } = resData;
      if (code === 200) {
        return {
          neutralLineInfo: data
        };
      }
      return new Promise.reject(resData);
    }
  } catch (error) {
    if (error) {
      return Promise.reject({
        code: 400,
        error: error
      });
    }
  }
}

function genImage(option, filename, folder) {
  const path = `${filename}.png`;
  let _folder = null;
  if (folder.endsWith("//") || folder.endsWith("/")) {
    _folder = folder;
  } else {
    _folder = folder + "//";
  }
  nodeEcharts({
    width: 500,
    height: 300,
    option,
    path: _folder + path,
    enableAutoDispose: true
  });
  return path;
}

async function genWeekly106Images(
  deviceId = "f72cfbca-5a91-4617-8f25-0c60b0376d20",
  folder = "C://images"
) {
  /**
   * 获取电流、温度线上数据
   */
  try {
    const images = [];
    const { currentInfo, temperatureInfo } = await getHttpDatas(deviceId);

    const { harmonicInfo } = await getXieBoDatas(deviceId);

    const { neutralLineInfo } = await getZhongXingXianDatas(deviceId);

    if (currentInfo) {
      // A相电流最大值
      if (currentInfo[12]) {
        const option = genCurrentOption({
          title: "A相电流最大值",
          type: 12,
          maxValue: currentInfo[12].maxValue,
          thresholdValue: currentInfo[12].thresholdValue,
          maxValueDate: currentInfo[12].maxValueDate,
          x: currentInfo[12].x,
          y: currentInfo[12].y
        });
        const filename = genImage(option, "A相电流最大值", folder);
        images.push(filename);
      }

      // B相电流最大值
      if (currentInfo[13]) {
        const option = genCurrentOption({
          title: "B相电流最大值",
          type: 13,
          maxValue: currentInfo[13].maxValue,
          thresholdValue: currentInfo[13].thresholdValue,
          maxValueDate: currentInfo[13].maxValueDate,
          x: currentInfo[13].x,
          y: currentInfo[13].y
        });
        const filename = genImage(option, "B相电流最大值", folder);
        images.push(filename);
      }

      // C相电流最大值
      if (currentInfo[14]) {
        const option = genCurrentOption({
          title: "C相电流最大值",
          type: 14,
          maxValue: currentInfo[14].maxValue,
          thresholdValue: currentInfo[14].thresholdValue,
          maxValueDate: currentInfo[14].maxValueDate,
          x: currentInfo[14].x,
          y: currentInfo[14].y
        });
        const filename = genImage(option, "C相电流最大值", folder);
        images.push(filename);
      }

      // 剩余电流最大值
      if (currentInfo[63]) {
        const option = genCurrentOption({
          title: "剩余电流最大值",
          type: 63,
          maxValue: currentInfo[63].maxValue,
          thresholdValue: currentInfo[63].thresholdValue,
          maxValueDate: currentInfo[63].maxValueDate,
          x: currentInfo[63].x,
          y: currentInfo[63].y
        });
        const filename = genImage(option, "剩余电流最大值", folder);
        images.push(filename);
      }
    }

    if (temperatureInfo) {
      // A相线缆最高温度
      if (temperatureInfo[5]) {
        const option = genTempureOption({
          title: "A相线缆最高温度",
          type: 5,
          maxValue: temperatureInfo[5].maxValue,
          thresholdValue: temperatureInfo[5].thresholdValue,
          maxValueDate: temperatureInfo[5].maxValueDate,
          x: temperatureInfo[5].x,
          y: temperatureInfo[5].y
        });
        const filename = genImage(option, "A相线缆最高温度", folder);
        images.push(filename);
      }

      // B相线缆最高温度
      if (temperatureInfo[6]) {
        const option = genTempureOption({
          title: "B相线缆最高温度",
          type: 6,
          maxValue: temperatureInfo[6].maxValue,
          thresholdValue: temperatureInfo[6].thresholdValue,
          maxValueDate: temperatureInfo[6].maxValueDate,
          x: temperatureInfo[6].x,
          y: temperatureInfo[6].y
        });
        const filename = genImage(option, "B相线缆最高温度", folder);
        images.push(filename);
      }

      // C相线缆最高温度
      if (temperatureInfo[7]) {
        const option = genTempureOption({
          title: "C相线缆最高温度",
          type: 7,
          maxValue: temperatureInfo[7].maxValue,
          thresholdValue: temperatureInfo[7].thresholdValue,
          maxValueDate: temperatureInfo[7].maxValueDate,
          x: temperatureInfo[7].x,
          y: temperatureInfo[7].y
        });
        const filename = genImage(option, "B相线缆最高温度", folder);
        images.push(filename);
      }

      // N相线缆最高温度
      if (temperatureInfo[8]) {
        const option = genTempureOption({
          title: "N相线缆最高温度",
          type: 8,
          maxValue: temperatureInfo[8].maxValue,
          thresholdValue: temperatureInfo[8].thresholdValue,
          maxValueDate: temperatureInfo[8].maxValueDate,
          x: temperatureInfo[8].x,
          y: temperatureInfo[8].y
        });
        const filename = genImage(option, "N相线缆最高温度", folder);
        images.push(filename);
      }
    }

    // 谐波数据
    if (harmonicInfo) {
      const option = genHarmonicOption(harmonicInfo);
      const filename = genImage(option, "谐波", folder);
      images.push(filename);
    }

    // 中性线数据
    if (neutralLineInfo) {
      const option = genNeutralLineOption(neutralLineInfo);
      const filename = genImage(option, "中性线", folder);
      images.push(filename);
    }

    return images;
  } catch (error) {
    return Promise.reject({
      code: 400,
      error: error
    });
  }
}

module.exports = genWeekly106Images;
